<template>
    <el-dialog :visible.sync="isShow" :title="headerTitle" @close="handleClose" center top="14vh" width="364px" append-to-body :fullscreen="fullscreen" @open="onOpen">
        <el-form :model="dialogForm" size="small" label-position="top" label-suffix=":" ref="detailForm" :rules="rules" label-width="80px">
            <!--              编号：-->
            <el-form-item :label="$t('basicData.code')" prop="stemLocationCode">
                <el-input v-model="dialogForm.stemLocationCode" :placeholder="$t('public.inputPl')" clearable />
            </el-form-item>
            <!--              名称：-->
            <el-form-item :label="$t('basicData.name')" prop="stemLocationName">
                <el-input v-model="dialogForm.stemLocationName" :placeholder="$t('public.inputPl')" clearable />
            </el-form-item>
            <!--              厂区：-->
            <el-form-item ref="factoryName" :label="$t('mtool.factoryName')" prop="factoryName">
                <el-autocomplete style="width:100%" popper-class="my-autocomplete" v-model="dialogForm.factoryName" :fetch-suggestions="factoryRemoteMethod" placeholder="请输入内容" @blur="handleFactoryBlur" @select="handleFactorySelect">
                    <i class="el-icon-search el-input__icon" slot="suffix">
                    </i>
                    <template slot-scope="{ item }">
                        {{ item.factoryName }}
                    </template>
                </el-autocomplete>
            </el-form-item>
            <!--              描述信息：-->
            <el-form-item ref="deviceName" :label="$t('basicData.description')" prop="description">
                <el-input v-model="dialogForm.description" type="textarea" maxlength="1000" :placeholder="$t('public.inputPl')" clearable />
            </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
            <el-button type="primary" @click="submitForm" :loading="loading" icon="el-icon-document" size="small">{{$t('public.save')}}</el-button>
        </div>
    </el-dialog>
</template>

<script>
import { listAllStemLocationMessage } from '@/api/basic/gaugeMessage'
import { addStemLocation, updateStemLocation } from '@/api/basic/stemLocation'
import { listALLFactory } from '@/api/basic/factory'
import EnjoySelectUser from '@/components/EnjoySelectUser'
import EnjoySelectDeptTree from '@/components/EnjoySelectDeptTree'
import FileUploadInput from '@/components/FileUploadInput'

export default {
    name: 'flaw-detial',
    components: { EnjoySelectUser, EnjoySelectDeptTree, FileUploadInput },

    props: {
        stemForm: {
            type: Object,
        },
        visible: {
            type: Boolean,
            default: false,
        },
        type: [String, Number], //1:新增  2：编辑 3：查看
    },
    computed: {
        isShow: {
            get() {
                return this.visible
            },
            set() {},
        },
        headerTitle() {
            const { type } = this
            let title = ''
            if (type == 1) {
                title =
                    this.$t('public.add') +
                    ' ' +
                    this.$t('basicData.ContainmentLocation')
            }
            if (type == 2) {
                title =
                    this.$t('public.edit') +
                    ' ' +
                    this.$t('basicData.ContainmentLocation')
            }

            return title
        },
    },
    data() {
        return {
            loading: false,
            fullscreen: false,
            deviceOptions: undefined,
            factoryOptions: undefined,
            dialogForm: {
                stemLocationCode: undefined,
                stemLocationName: undefined,
                factoryName: undefined,
            },
            // 表单校验
            rules: {
                stemLocationCode: [
                    {
                        required: true,
                        message: '编号不能为空',
                        trigger: 'blur',
                    },
                ],
                stemLocationName: [
                    {
                        required: true,
                        message: '名称不能为空',
                        trigger: 'blur',
                    },
                ],
                factoryName: [
                    {
                        required: true,
                        message: this.$t('formValidation.factoryAreaCannotBeEmpty'),
                        trigger: 'blur',
                    },
                ],
            },
            restaurants: [],
            timeout: null,
        }
    },
    watch: {
        visible(val) {
            if (val) {
                this.getFactorySelect()
            }
        },
    },
    methods: {
        // 窗口打开
        onOpen() {
            this.dialogForm = { ...this.stemForm }
        },
        /** 发起提交 */
        submitForm: function () {
            this.$refs.detailForm.validate((valid) => {
                let action =
                    this.type == 1 ? addStemLocation : updateStemLocation
                if (valid) {
                    this.loading = true
                    action(this.dialogForm).then(
                        (res) => {
                            this.loading = false
                            if (res.code == 200) {
                                this.$emit('refresh')
                                this.$modal.msgSuccess('操作成功!')
                                this.$emit('update:visible', false)
                            }
                        },
                        (err) => {
                            this.loading = false
                        }
                    )
                }
            })
        },
        handleClose(done) {
            this.$emit('update:visible', false)
            this.$refs['detailForm'].resetFields()
        },

        //工厂模糊查询
        factoryRemoteMethod(val, cb) {
            // listALLFactory({factoryName:val}).then(res=>{
            //   this.factoryOptions = res.data.map(i=>i.deviceName)
            //   cb(res.data)
            // })
            let restaurants = this.restaurants
            let results = val
                ? restaurants.filter(this.createStateFilter(val))
                : restaurants
            clearTimeout(this.timeout)
            this.timeout = setTimeout(() => {
                cb(results)
            }, 1000 * Math.random())
        },
        createStateFilter(queryString) {
            return (state) => {
                return (
                    state.factoryName
                        .toLowerCase()
                        .indexOf(queryString.toLowerCase()) === 0
                )
            }
        },
        getFactorySelect() {
            listALLFactory().then((res) => {
                this.factoryOptions = res.data.map((i) => i.deviceName)
                this.restaurants = res.data
            })
        },
        handleFactorySelect(e) {
            this.dialogForm.factoryName = e.factoryName
            this.$refs.factoryName.$emit('el.form.blur')
        },
        handleFactoryBlur(e) {
            const { factoryOptions, dialogForm } = this
            if (!factoryOptions.includes(dialogForm.factoryName)) {
                this.dialogForm.factoryName = ''
            }
        },
        handleExpireTime(e) {
            console.log(e)
            const today = new Date().getTime()
            const val = new Date(e).getTime()
            if (val > today) {
                this.dialogForm.remDay = ~~(
                    (val - today) /
                    1000 /
                    60 /
                    60 /
                    24
                ).toFixed(1)
            } else {
                this.dialogForm.remDay = 0
            }
            this.$forceUpdate()
        },
        handleRespName(e) {
            this.dialogForm.respName = e.name
        },
        handleEmployName(e) {
            this.dialogForm.employName = e.name
        },
        handleRespDept(e) {
            this.dialogForm.respDept = e.name
        },
    },
}
</script>

<style scoped>
::v-deep .el-form--label-top .el-form-item__label {
    padding: 0;
}
</style>
